Java syntax
part 5/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Integer literals are of int type by default unless long type is specified by appending L or l suffix to the literal, e.g. 367L. Since Java SE 7, it is possible to include underscores between the digits of a number to increase readability; for example, a number 145608987 can be written as 145_608_987.
Variables
Variables are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.
int count; //Declaring an uninitialized variable called 'count', of type 'int'
count = 35; //Initializing the variable
int count = 35; //Declaring and initializing the variable at the same time
Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.
int a, b; //Declaring multiple variables of the same type
int a = 2, b = 3; //Declaring and initializing multiple variables of the same type
Type inference
Since Java 10, it has become possible to infer types for the variables automatically by using var.
// stream will have the FileOutputStream type as inferred from its initializer
var stream = new FileOutputStream("file.txt");
// An equivalent declaration with an explicit type
FileOutputStream stream = new FileOutputStream("file.txt");
Code blocks